package com.zzg.cloud.dto;

import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;

@Slf4j
public abstract class BaseFallBackFactory<T> implements FallbackFactory<T> {

    private static final String FEIGN_ERROR_MSG = "服务熔断，请联系开发人员检查";

    private Class<T> tClass;

    private T obj;

    public BaseFallBackFactory(){
        tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        obj = (T) Proxy.newProxyInstance(BaseFallBackFactory.class.getClassLoader(), new Class[]{tClass}, (Object proxy, Method method, Object[] args) -> {
            Class<?> returnType = method.getReturnType();
            if (returnType.isAssignableFrom(RespResult.class)) {
                return RespResult.failed(FEIGN_ERROR_MSG);
            }else {
                log.error("{}, method: {}, args: {}", FEIGN_ERROR_MSG, method.getName(), args);
                return returnType.newInstance();
            }
        });
    }

    @Override
    public T create(Throwable cause) {
        log.error("服务熔断，请联系开发人员检查,错误信息: " + cause.getMessage(), cause);
        return obj;
    }

}
